<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\admin\logic;

/**
 * 会员逻辑
 */
class User extends AdminBase
{
    /**
     * 服务商分润列表
     */
    public function getServiceMoneyList($where = [], $field = '*', $order = 'id desc', $paginate = DB_LIST_ROWS)
    {
        $list=$this->modelServiceMoney->getList($where, $field, $order, $paginate);
        return $list;
    }
    /**
     * 服务商分润
     */
    public function moneyService($data = [])
    {
        $url = url('serviceMoney');
        $list=db('user')->where('grade',3)->column('id');
        $sjlist=db('user')->where('grade',5)->column('id');
        $qxlist=db('user')->where('grade',6)->column('id');
        $info=[];
        $info['sum']=db('user')->where('id',10006)->value('moneyMy');
        if(empty($info['sum'])){
            return [RESULT_SUCCESS, '余额不足'];
        }
        $info['f3']=count($list);
        $info['f2']=count($sjlist);
        $info['f1']=count($qxlist);
        $info['qxfws']=floor($info['sum']/7*3*100/$info['f1'])/100;
        $info['sjfws']=floor($info['sum']/7*2*100/$info['f2'])/100;
        $info['fws']=floor($info['sum']/7*2*100/$info['f3'])/100;
        $info['add_time']=date('Y-m-d H:i:s');
        $info['member_id']=MEMBER_ID;
        db('service_money')->startTrans();
        $result=db('service_money')->insert($info);
        $res=moneyyj_log($info['sum']*(-1),10006,20,10006,MEMBER_ID);
        foreach($list as $v){
            moneyyj_log($info['fws'],$v,19,10006,MEMBER_ID);
        }
        foreach($sjlist as $v){
            moneyyj_log($info['sjfws'],$v,21,10006,MEMBER_ID);
        }
        foreach($qxlist as $v){
            moneyyj_log($info['qxfws'],$v,22,10006,MEMBER_ID);
        }
        if($result && $res){
            db('service_money')->commit();
            action_log('服务商分润', '服务商分润');
        }else{
            db('service_money')->rollback();
        }
        return $result ? [RESULT_SUCCESS, '服务商分润', $url] : [RESULT_ERROR, '操作失败'];
    }
    /**
     * 获取申请列表
     */
    public function getsjList($where = [], $field = 'm.*,b.username,b.name,b.is_gh', $order = 'm.id desc', $paginate = DB_LIST_ROWS)
    {

        $this->modelSj->alias('m');

        $join = [
            [SYS_DB_PREFIX . 'user b', 'm.user_id = b.id', 'LEFT'],
        ];
        // $where['m.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];
        $this->modelSj->join = $join;
        $list=$this->modelSj->getList($where, $field, $order, $paginate);
        return $list;
    }
	/**
     * 获取会员资料列表
     */
    public function getAttestationList($where = [], $field = 'm.*,b.username,b.name', $order = 'm.id asc', $paginate = DB_LIST_ROWS)
    {
        
        $this->modelAttestation->alias('m');
        
        $join = [
                    [SYS_DB_PREFIX . 'user b', 'm.user_id = b.id', 'LEFT'],
                ];
        
       // $where['m.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];
       
        $this->modelAttestation->join = $join;
        
        $list = $this->modelAttestation->getList($where, $field, $order, $paginate);
		foreach($list as $k=>$v){
			$list[$k]['title']=db('goods')->where('id',$v['gid'])->value('title');
			$list[$k]['zxlist']=explode(',',substr($v['zx'],0,-1));
			$list[$k]['lslist']=explode(',',substr($v['ls'],0,-1));
			$list[$k]['addlist']=explode(',',substr($v['add'],0,-1));
			$list[$k]['banklist']=explode(',',substr($v['bank'],0,-1));
			$list[$k]['drivelist']=explode(',',substr($v['drive'],0,-1));
		}
		return $list;
    }
	/**
     * 获取会员列表
     */
    public function getDiskGroupList($data)
    {
		$where = [];
        !empty($data['search_data']) && $where['ids'] = ['like', '%'.$data['search_data'].'%'];       
        return $this->modelDiskGroup->getList($where, '*', 'id desc',DB_LIST_ROWS);
    }
	/**
     * 获取会员列表
     */
    public function getDiskList($where = [], $field = 'm.*,b.username,b.name', $order = 'm.diskGroup asc,m.diskNum asc', $paginate = DB_LIST_ROWS)
    {
        
        $this->modelDisk->alias('m');
        
        $join = [
                    [SYS_DB_PREFIX . 'user b', 'm.user_id = b.id', 'LEFT'],
                ];
        
       // $where['m.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];
        
        $this->modelDisk->join = $join;
        
        return $this->modelDisk->getList($where, $field, $order, $paginate);
    }
    /**
     * 冻结团队
     */
    public function frozenUser($data)
    {
        $nocodea=db('user')->where(array('username'=>$data['username']))->value('id');
        if(empty($nocodea)){
            return [RESULT_ERROR, '不存在该用户'];
        }else{
            if($data['dj'] == 1){
                $msg=array('status'=>0);
            }else{
                $msg=array('status'=>1);
            }
            $result=db('user')->where("id=".$nocodea." or nocodea like '%$nocodea%'")->update($msg);
            $result && action_log('冻结用户团队', '冻结用户团队，username：' . $data['username']);
            if($result){
                echo json_encode(array('code'=>0,'msg'=>'操作成功'));exit;
            }else{
                echo json_encode(array('code'=>1,'msg'=>'操作失败'));exit;
            }
        }
    }
    
    /**
     * 获取会员信息
     */
    public function getUserInfo($where = [], $field = true)
    {
        
        $info = $this->modelUser->getInfo($where, $field);
        
        $info['leader_username'] = $this->modelUser->getValue(['id' => $info['tjid']], 'username');
        $info['tjname'] = $this->modelUser->getValue(['id' => $info['tjid']], 'name');
        return $info;
    }
    /**
     * 导出拨付列表
     */
    public function exportMoneyyjList($where = [])
    {
        $list = $this->modelMoneyyj->getList($where,'*','id DESC', false);
        foreach($list as $k=>$v){
            $list[$k]['str']=moneyyjTypes($v['type'],$v['getid']);
            $list[$k]['username']=db('user')->where('id',$v['user_id'])->value('username');
            $list[$k]['name']=db('user')->where('id',$v['user_id'])->value('name');
            if(!empty($v['getid'])){
                $list[$k]['names']=db('member')->where('id',$v['getid'])->value('username');
            }else{
                $list[$k]['names']='';
            }
        }
        $titles = "描述,金额,拨付用户,昵称,时间,用户类型,拨付管理员,备注";
        $keys   = "str,money,username,name,create_time,names,beizhu";

        action_log('导出', '导出拨付列表');
        export_excel($titles, $keys, $list, '拨付列表');
    }
    /**
     * 导出会员列表
     */
    public function exportUserList($where = [], $field = 'm.*,b.username as tjusername,b.name as tjname', $order = '')
    {
        
        $list = $this->getUserList($where, $field, $order, false);
        foreach($list as $k=>$v){
            $list[$k]['service']=$v['is_service']==1?'代理商':' ';
            $list[$k]['is']=$v['is']==1?'商家':' ';
            $list[$k]['grade']=userSf($v['grade']);
            $list[$k]['tjnum']=db('user')->where('tjid',$v['id'])->count();
            $list[$k]['status']=$v['status']==1?'正常':'禁用';
        }
        $titles = "用户名,昵称,分享人,代理类型,商家类型,用户类型,直推数量,余额,积分,消费券,注册时间,状态";
        $keys   = "username,name,tjusername,service,is,grade,tjnum,moneyMy,count,xfq,create_time,status";
        
        action_log('导出', '导出用户列表');
        
        export_excel($titles, $keys, $list, '用户列表');
    }	
    /**
     * 获取会员列表
     */
    public function getUserList($where = [], $field = 'm.*,b.username as tjusername,b.name as tjname', $order = 'id asc', $paginate = DB_LIST_ROWS)
    {
        
        $this->modelUser->alias('m');
        
        $join = [
                    [SYS_DB_PREFIX . 'user b', 'm.tjid = b.id', 'LEFT'],
                ];
        
        $where['m.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];
        
        $this->modelUser->join = $join;
        
        return $this->modelUser->getList($where, $field, $order, $paginate);
    }
	/**
     * 获取会员列表搜索条件
     */
    public function getWhere($data = [])
    {
        
        $where = [];
        !empty($data['search_data']) && $where['m.name|m.username|m.phone|m.sbh'] = ['like', '%'.$data['search_data'].'%'];
        !empty($data['tjid']) && $where['m.tjid']=$data['tjid'];
		!empty($data['is']) && $where['m.is']=$data['is'];
        !empty($data['gsrz']) && $where['m.gsrz']=$data['gsrz'];
        !empty($data['grade']) && $where['m.grade']=$data['grade'];
        return $where;
    }
    
    /**
     * 会员添加
     */
    public function userAdd($data = [])
    {
        
        $validate_result = $this->validateUser->scene('add')->check($data);
        
        if (!$validate_result) {
            
            return [RESULT_ERROR, $this->validateUser->getError()];
        }
        
        $url = url('userList');
        
        $info=db("user")->field("id,nocodea")->where('username',$data['tjusername'])->find();
		if(empty($info)){
			return [RESULT_ERROR, '不存在该分享人'];
		}
        $salt=rand(1000,9999);
        $data['salt'] = $salt;
		$data['tjid']=$info['id'];
		$data['nocodea'] = $info['nocodea'].$data['tjid'].',';
		$data['password'] = data_md5_key($data['password'],$salt);
        $data['passwords'] = data_md5_key($data['password'],$salt);
		$data['invitation']=initcode();
        $result = $this->modelUser->setInfo($data);
		//$nocodea=$info['nocodea'].$result.',';
		//$res=db('user')->where('id',$result)->update(array('nocodea'=>$nocodea));
        $result && action_log('新增', '新增用户，username：' . $data['username']);
        
        return $result ? [RESULT_SUCCESS, '用户添加成功', $url] : [RESULT_ERROR, $this->modelUser->getError()];
    }
    
    /**
     * 会员编辑
     */
    public function userEdit($data = [])
    {
        
        $validate_result = $this->validateUser->scene('edit')->check($data);
        
        if (!$validate_result) {
            
            return [RESULT_ERROR, $this->validateUser->getError()];
        }
        $url = url('userList');
        if($data['tjuser'] != $data['tjusername']){
            $info=db('user')->field('id,name,nocodea')->where('username',$data['tjusername'])->find();
            if(empty($info)){
                return [RESULT_ERROR, '不存在该分享人'];
            }
            if($info['id'] == $data['id']){
                return [RESULT_ERROR, '分享人不能为本人'];
            }else{
                $arr=explode(',',$info['nocodea']);
                if(in_array($data['id'],$arr)){
                    return [RESULT_ERROR, '该用户为自己团队人员，不能作为分享人'];
                }
            }
            db('user')->startTrans();
            $nocodea=db('user')->where('id',$data['id'])->value('nocodea');
            $data['tjid']=$info['id'];
            $data['nocodea']=$info['nocodea'].$info['id'].',';
            $result = $this->modelUser->setInfo($data);
            $str=','.$data['id'].',';
            $list=db('user')->field('id,nocodea')->where("nocodea like '%$str%'")->select();
            if(!empty($list)){
                foreach($list as $k=>$v){
                    $thnocodeas=$info['nocodea'].$info['id'].',';
                    $str1=str_replace($nocodea,$thnocodeas,$v['nocodea']);
                    $res=db('user')->where('id',$v['id'])->update(array('nocodea'=>$str1));
                }
            }else{
                $res =true;
            }
            if($result && $res){
                db('user')->commit();
                action_log('编辑', '编辑用户，id：' . $data['id'].'；分享人变动：'.$data['tjuser'].'=>'.$data['tjusername']);
            }else{
                db('user')->rollback();
            }
        }else{
            $result = $this->modelUser->setInfo($data);
            $result && action_log('编辑', '编辑用户，id：' . $data['id']);
        }
        return $result ? [RESULT_SUCCESS, '用户编辑成功', $url] : [RESULT_ERROR, $this->modelUser->getError()];
    }
    
	/**
     * 获取申请列表
     */
    public function getApplyList($where = [], $field = 'm.*,b.username,b.name', $order = '', $paginate = DB_LIST_ROWS)
    {
        
        $this->modelApply->alias('m');
        
        $join = [
                    [SYS_DB_PREFIX . 'user b', 'm.user_id = b.id', 'LEFT'],
                ];
        
       // $where['m.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];
        
        $this->modelApply->join = $join;
        $list=$this->modelApply->getList($where, $field, $order, $paginate);
        return $list;
    }
	/**
     * 获取会员列表搜索条件
     */
    public function getWheres($data = [])
    {
        $where = [];
        isset($data['stat']) && $data['stat']!=9 && $where['m.stat']=$data['stat'];
        !empty($data['search_data']) && $where['m.company|b.username|b.name'] = ['like', '%'.$data['search_data'].'%'];        
        //!empty($data['tjid']) && $where['m.tjid']=$data['tjid'];
        return $where;
    }
	/**
     * 余额明细
     */
    public function getMoneyyjList($where)
    {
        return $this->modelMoneyyj->getList($where,'*','id DESC');
    }
	/**
     * 权限明细
     */
    public function getLogList($data)
    {
        $where = [];     
        !empty($data['user_id']) && $where['user_id'] = $data['user_id'];
		isset($data['type']) && $where['type'] = $data['type'];
        !empty($data['key']) && $where['key'] = $data['key'];
        !empty($data['search_data']) && $where['user_id'] = ['like', '%'.$data['search_data'].'%'];
        return $this->modelLog->getList($where,'*','id DESC');
    }
    /**
     * 服务商列表
     */
    public function getAgentList($where = [], $field = 'm.*,b.username,b.name', $order = 'm.create_time desc', $paginate = DB_LIST_ROWS)
    {

        $this->modelAgent->alias('m');

        $join = [
            [SYS_DB_PREFIX . 'user b', 'm.user_id = b.id', 'LEFT'],
        ];

        $where['m.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];

        $this->modelAgent->join = $join;
        $list=$this->modelAgent->getList($where, $field, $order, $paginate);
        foreach($list as $k=>$v){
            $list[$k]['address']=db('region')->where('code',$v['code'])->value('name');
        }
        return $list;
    }
    /**
     * 服务商列表
     */
    public function getServiceList($where = [], $field = 'm.*,b.username,b.name as names', $order = 'm.create_time desc', $paginate = DB_LIST_ROWS)
    {

        $this->modelService->alias('m');

        $join = [
            [SYS_DB_PREFIX . 'user b', 'm.user_id = b.id', 'LEFT'],
        ];

        $where['m.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];

        $this->modelService->join = $join;
        $list=$this->modelService->getList($where, $field, $order, $paginate);
        foreach($list as $k=>$v){
            $list[$k]['addresss']=db('region')->where('code',$v['code'])->value('name');
        }
        return $list;
    }
    /**
     * 服务商添加
     */
    public function serviceAdd($data = [])
    {
        $url = url('serviceList');
        if(empty($data['id'])){
            if (empty($data['username']) || empty($data['name']) || empty($data['addresss'])) {
                return [RESULT_ERROR, '请输入完整信息'];
            }else{
                $user_id=db('user')->where('username',$data['username'])->value('id');
                if(empty($user_id)){
                    return [RESULT_ERROR, '请输入正确用户名'];
                }
                $is=db('service')->where('user_id',$user_id)->value('id');
                if(!empty($is)){
                    return [RESULT_ERROR, '请用户已成为服务商，不能重复提交'];
                }
                $a=$data['addresss'];
                $region=db('region')->field('code,level')->where("name like '%$a%'")->find();
                if(empty($region)){
                    return [RESULT_ERROR, '没有查询到该地址'];
                }
                $is=db('service')->where('code',$region['code'])->value('id');
                if(!empty($is)){
                    return [RESULT_ERROR, '该地区已存在服务商，请选择其他区域'];
                }
            }
            $data['user_id']=$user_id;
            $data['code']=$region['code'];
            $data['level']=$region['level'];
            $data['create_time']=time();
            $res=db('service')->insertGetId($data);
            $res && action_log('新增', '新增服务商，id：' . $res);
            db('user')->where('id',$user_id)->update(array('is_service'=>1));
        }else{
            $a=$data['addresss'];
            $region=db('region')->field('code,level')->where("name like '%$a%'")->find();
            if(empty($region)){
                return [RESULT_ERROR, '没有查询到该地址'];
            }
            $is=db('service')->where("id!=".$data['id']." and code=".$region['code'])->value('id');
            if(!empty($is)){
                return [RESULT_ERROR, '该地区已存在服务商，请选择其他区域'];
            }
            $data['code']=$region['code'];
            $data['level']=$region['level'];
            $res=db('service')->where('id',$data['id'])->update($data);
            $res && action_log('编辑', '编辑服务商信息，id：' . $data['id']);
        }
        return $res ? [RESULT_SUCCESS, '操作成功', $url] : [RESULT_ERROR, '操作失败'];
    }
    /**
     * 获取会员列表
     */
    public function getChatList($where = [], $field = 'm.*,b.username,b.name,b.headimg,b.is_service,b.is,b.gsrz,b.id as resume', $order = 'm.create_time desc', $paginate = DB_LIST_ROWS)
    {

        $this->modelChat->alias('m');

        $join = [
            [SYS_DB_PREFIX . 'user b', 'm.getid = b.id', 'LEFT'],
        ];

        $where['m.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];

        $this->modelChat->join = $join;

        return $this->modelChat->getList($where, $field, $order, $paginate);
    }
    /**
     * 获取会员列表
     */
    public function getChatLists($where = [], $field = 'm.*,b.username,b.name,b.headimg,b.is_service,b.is,b.gsrz,b.id as resume', $order = 'm.create_time desc', $paginate = DB_LIST_ROWS)
    {

        $this->modelChat->alias('m');

        $join = [
            [SYS_DB_PREFIX . 'user b', 'm.user_id = b.id', 'LEFT'],
        ];

        $where['m.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];

        $this->modelChat->join = $join;

        return $this->modelChat->getList($where, $field, $order, $paginate);
    }
    /**
     * 获取会员列表
     */
    public function getShoucangList($where = [], $field = '*', $order = 'create_time desc', $paginate = DB_LIST_ROWS)
    {
        $list=$this->modelShoucang->getList($where, $field, $order, $paginate);
        foreach($list as $k=>$v){
            $user_id=db('resume')->where('resume_id',$v['resume_id'])->value('user_id');
            $info=db('user')->field('username,name,headimg,gsrz,is,is_service')->where('id',$user_id)->find();
            $list[$k]['username']=$info['username'];
            $list[$k]['name']=$info['name'];
            $list[$k]['headimg']=$info['headimg'];
            $list[$k]['gsrz']=$info['gsrz'];
            $list[$k]['is']=$info['is'];
            $list[$k]['resume']=$user_id;
            $list[$k]['is_service']=$info['is_service'];
        }
        return $list;
    }
    /**
     * 获取会员列表
     */
    public function getInterviewList($where = [], $field = '*', $order = 'create_time desc', $paginate = DB_LIST_ROWS)
    {
        $list=$this->modelInterview->getList($where, $field, $order, $paginate);
        foreach($list as $k=>$v){
        
            $info=db('user')->field('username,name,headimg,gsrz,is,is_service')->where('id',$v['getid'])->find();
            $list[$k]['username']=$info['username'];
            $list[$k]['name']=$info['name'];
            $list[$k]['headimg']=$info['headimg'];
            $list[$k]['gsrz']=$info['gsrz'];
            $list[$k]['is']=$info['is'];
            $list[$k]['resume']=$v['getid'];
            $list[$k]['is_service']=$info['is_service'];
        }
        return $list;
    }
    /**
     * 获取会员列表
     */
    public function getUsersList($where = [], $field = 'm.*,b.resume_id', $order = 'm.id desc', $paginate = DB_LIST_ROWS)
    {
        $this->modelUser->alias('m');
        $join = [
            [SYS_DB_PREFIX . 'resume b', 'm.id = b.user_id', 'LEFT'],
        ];
        $where['m.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];

        $this->modelUser->join = $join;

        return $this->modelUser->getList($where, $field, $order, $paginate);
    }
    /**
     * 获取投递用户列表
     */
    public function getResumeLists($where = [], $field = '*', $order = 'create_time desc', $paginate = DB_LIST_ROWS)
    {
        $list=$this->modelDeliverResume->getList($where, $field, $order, $paginate);
        foreach($list as $k=>$v){
            $info=db('user')->field('username,name,headimg,gsrz,is,is_service')->where('id',$v['user_id'])->find();
            $list[$k]['username']=$info['username'];
            $list[$k]['name']=$info['name'];
            $list[$k]['headimg']=$info['headimg'];
            $list[$k]['gsrz']=$info['gsrz'];
            $list[$k]['is']=$info['is'];
            $list[$k]['resume']=$v['user_id'];
            $list[$k]['is_service']=$info['is_service'];
        }
        return $list;
    }
    /**
     * 数据状态设置
     */
    public function setGh($param = null)
    {

        if (empty($param)) {

            return [RESULT_ERROR, '非法操作'];
        }
        $result=db('user')->where('id',$param['id'])->update(['is_gh'=>$param['is_gh']]);
        $result && action_log('供货商身份', '供货商身份状态调整' . '，is_gh：' . $param['is_gh']);
        return $result ? [RESULT_SUCCESS, '操作成功'] : [RESULT_ERROR, '操作失败'];
    }
}
